<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>题库管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/admin.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">试题名</label>
                    <div class="layui-input-block">
                        <input type="text" name="quesName" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY-user-front-search">
                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                    </button>
                </div>
            </div>
        </div>

        <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="batchdel">删除</button>
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="add">添加</button>
            </div>

            <table id="LAY-user-manage" lay-filter="LAY-user-manage"></table>
            <table id="LAY-ques-detail" lay-filter="LAY-ques-detail"></table>

            <script type="text/html" id="table-quesTool">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="detail"><i
                        class="layui-icon "></i>查看</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i
                        class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
        </div>
    </div>
</div>

<script src="/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'element', 'table'], function () {
        const $ = layui.$;
        const form = layui.form;
        const element = layui.element;
        const table = layui.table;

        // 渲染试题界面
        table.render({
            elem: "#LAY-user-manage",
            url: 'quesManagement/quesList',
            cols: [[{type: "checkbox", fixed: "left"},
                {field: "quesName", title: "试题名", width: 140, align: "center", edit: "text"},
                {field: "count", title: "题数", width: 140, align: "center"},
                {
                    title: "操作",
                    width: 150,
                    align: "center",
                    fixed: "right",
                    toolbar: "#table-quesTool"
                }
            ]],
            page: true,
            parseData: function(res){
                let data = res.data;
                for (let item in data) {
                    data[item].count = data[item].quesContent.length;
                }
                return {
                    "code": res.status, //解析接口状态
                    "count": res.count, //解析数据长度
                    "data": data //解析数据列表
                };
            }
        });

        // 监听 编辑
        let oData = {};
        let edit = function(obj){
            let data = obj.data;

            if (Object.keys(data).length === 1 && oData.stringify !== "{}") {
                for (let item in oData.quesContent) {
                    delete oData.quesContent[item].LAY_TABLE_INDEX
                }
                data = oData;
            }
            // 发起修改请求
            $.ajax({
                type: "post",
                url: "/admin/views/quesManagement/update",
                data,
                success(res){
                    console.log(res);
                    if(res.status === 200) {

                    }
                },
                fail(err){
                    layer.msg("请求超时", {
                        anim: 5,
                        time: 1500
                    })
                }
            });
        };
        table.on('edit(LAY-user-manage)', edit);
        table.on('edit(LAY-ques-detail)', edit);

        // 监听每条数据的工具事件
        table.on('tool(LAY-user-manage)', function(obj){
            //console.log(data)
            let data = obj.data;
            let event = obj.event;
            let _id = data._id;
            let delData = [];
            delData.push({_id});

            switch(event){
                case 'detail':
                    table.render({
                        elem: $('#LAY-ques-detail'), //指定原始表格元素选择器
                        // limit: 200,
                        url: 'quesManagement/quesList',
                        cols: [[
                            {type: 'numbers', fixed: 'left'},
                            {field: 'ques', title: '试题', edit: 'text'},
                        ]],
                        parseData: function(res){
                            let data = res.data;

                            for (let item in data) {
                               if ( data[item]._id === _id) oData = data[item] //data.splice(item, 1);
                            }
                            //oData = data;
                            if (data.length !== 0) data = oData.quesContent;
                            //console.log(data)
                            return {
                                "code": res.status, //解析接口状态
                                "count": res.count, //解析数据长度
                                "data": data //解析数据列表
                            };
                        }
                    });
                    break;
                case 'del':
                    layer.confirm('确定删除吗？', {icon: 3, title:'提示'}, () => {
                        // 发起删除请求
                        $.ajax({
                            type: "post",
                            url: "/admin/views/quesManagement/delete",
                            data: {
                                data: delData
                            },
                            success(res){
                                console.log(res);
                                if(res.status === 200) {
                                    location.href = '/admin/views/quesManagement'; //后台主页
                                    layer.msg(`成功删除${res.data.deletedCount}条数据`);
                                }
                            },
                            fail(err){
                                layer.msg("请求超时", {
                                    anim: 5,
                                    time: 1500
                                })
                            }
                        });
                    });
                    break;
            }
        });

        //监听搜索
        let search = function (data) {
            let field = data.field;
            //console.log(field);
            // 过滤值为空字符串的属性
            for (const item in field) {
                if (field[item] === "") delete field[item];
            }
            //执行重载
            console.log(field);
            table.reload('LAY-user-manage', {
                where: field,
                done: function(res, curr, count){
                    // 清除本次参数
                    this.where={};
                }
            });
        };
        form.on('submit(LAY-user-front-search)', search);

        // 监听上方删除和添加事件
        let active = {
            // 监听删除
            batchdel: function () {
                let checkStatus = table.checkStatus('LAY-user-manage');
                let checkData = checkStatus.data; //得到选中的数据
                console.log(checkStatus);

                // 判断数据是否为空
                if (checkData.length === 0) {
                    return layer.msg('请选择数据');
                }

                layer.confirm('确定删除吗？', {icon: 3, title:'提示'}, () => {
                    // 发起删除请求
                    $.ajax({
                        type: "post",
                        url: "/admin/views/quesManagement/delete",
                        data: {
                            data: checkData
                        },
                        success(res){
                            console.log(res);
                            if(res.status === 200) {
                                //console.log(data)
                                table.reload('LAY-user-manage');
                                table.reload('LAY-ques-detail');
                                layer.msg(`成功删除${res.data.deletedCount}条数据`);
                            }
                        },
                        fail(err){
                            layer.msg("请求超时", {
                                anim: 5,
                                time: 1500
                            })
                        }
                    });
                });
            },
            add: function () {
                //     layer.open({
                //         type: 2
                //         , title: '添加用户'
                //         , content: 'userform.html'
                //         , maxmin: true
                //         , area: ['500px', '450px']
                //         , btn: ['确定', '取消']
                //         , yes: function (index, layero) {
                //             var iframeWindow = window['layui-layer-iframe' + index]
                //                 , submitID = 'LAY-user-front-submit'
                //                 , submit = layero.find('iframe').contents().find('#' + submitID);
                //
                //             //监听提交
                //             iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                //                 var field = data.field; //获取提交的字段
                //
                //                 //提交 Ajax 成功后，静态更新表格中的数据
                //                 //$.ajax({});
                //                 table.reload('LAY-user-front-submit'); //数据刷新
                //                 layer.close(index); //关闭弹层
                //             });
                //
                //             submit.trigger('click');
                //         }
                //     });
                // }
            }
        };

        $('.layui-btn.layuiadmin-btn-useradmin').on('click', function () {
            let type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>
</body>
</html>
